#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <sys/wait.h>
#include <pthread.h>
#include <functional>
#include <memory>
#include "InetAddr.hpp"
#include "Log.hpp"
#include "Socket.hpp"

using namespace std;
using namespace yss;

class TcpServer; // 声明

using http_t = function<string(string request)>;

class ThreadData
{
public:
    ThreadData(socket_sptr fd, InetAddr addr, TcpServer *s) : sockfd(fd), clientaddr(addr), self(s)
    {
    }

public:
    socket_sptr sockfd;
    InetAddr clientaddr;
    TcpServer *self;
};

class TcpServer
{
public:
    TcpServer(uint16_t port, http_t service)
        : _localaddr("0", port), _isrunning(false), _listensock(make_unique<TcpSocket>()),_http_service(service)
    {
        _listensock->BuildListenSocket(_localaddr);
    }
    
    static void *HandlerTask(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        string request, response;
        ssize_t n = td->sockfd->Recv(&request);// 读取请求
        if(n > 0)
        {
            response = td->self->_http_service(request);
            td->sockfd->Send(response);// 发送应答
        }

        close(td->sockfd->Sockfd()); 
        delete td;
        return nullptr;
    }
    void Loop()
    {
        _isrunning = true;
        // 不能直接获取数据，先获取连接
        while (_isrunning)
        {
            InetAddr peeraddr;
            socket_sptr normalsock = _listensock->Accepter(&peeraddr);
            if(normalsock == nullptr) continue;

            pthread_t tid;
            ThreadData *td = new ThreadData(normalsock, peeraddr, this);
            pthread_create(&tid, nullptr, HandlerTask, td); // 线程分离
        }

        _isrunning = false;
    }
    ~TcpServer()
    {
    }

private:
    unique_ptr<Socket> _listensock;
    InetAddr _localaddr;
    bool _isrunning;

    http_t _http_service;
};
